package com.example.springboot.controller;


import com.example.springboot.mapper.DepartmentMapper;
import com.example.springboot.mapper.EmployeeMapper;
import com.example.springboot.pojo.Department;
import com.example.springboot.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee> employees = employeeMapper.queryAll();
        model.addAttribute("emps",employees);
        return "emp/list";
    }

    @GetMapping("/toAdd")
    public String addEmployee(Model model){
        // 获得所有部门的信息
        Collection<Department> departments = departmentMapper.queryAll();

        model.addAttribute("departments",departments);

        return "emp/add";
    }


    // 添加员工表单提交过来
    @PostMapping("/emps")
    public String addEmp(Employee employee){
        // 添加的操作

        System.out.println("add-->"+employee);
        employeeMapper.addEmployee(employee);

        return "redirect:/emps";
    }



    // 去员工修改页面
    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id")Integer id,Model model){
        // 查出原来的数据

        Employee employee= employeeMapper.queryEmployeeById(id);
        model.addAttribute("emp",employee);

        // 获得所有部门的信息
        Collection<Department> departments = departmentMapper.queryAll();
        model.addAttribute("departments",departments);

        return "emp/update";
    }


    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        System.out.println("update-->"+employee);
        employeeMapper.updateEmployee(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/delete/{id}")
    public String deleteEmp(@PathVariable("id")Integer id){
        employeeMapper.deleteEmployee(id);
        return "redirect:/emps";
    }


    // 返回一个employee的bean
    @GetMapping("/employee")
    public Employee employee(){
        return new Employee();
    }

    // 返回一个department的bean
    @GetMapping("/department")
    public Department department(){
        return new Department();
    }



}
